package com.sx.ad.service.impl;

import com.sx.ad.constant.Constants;
import com.sx.ad.dao.AdUserRepository;
import com.sx.ad.entity.AdUser;
import com.sx.ad.exception.AdException;
import com.sx.ad.service.IUserService;
import com.sx.ad.utils.CommonUtils;
import com.sx.ad.vo.CreateUserRequest;
import com.sx.ad.vo.CreateUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zkx
 * @since 2024-08-23
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

	@Autowired
	private final AdUserRepository adUserRepository;

	public UserServiceImpl(AdUserRepository adUserRepository) {
		this.adUserRepository = adUserRepository;
	}

	@Override
	public CreateUserResponse createUser(CreateUserRequest request) throws AdException {
		if (!request.validate()){
			throw new AdException(Constants.ErrorMsg.REQUEST_PARAM_ERROR);
		}

		AdUser oldUser = adUserRepository.findByUsername(request.getUsername());
		if (oldUser != null){
			log.error("username:{} duplicate", request.getUsername());
			throw new AdException(Constants.ErrorMsg.SAME_NAME_ERROR);
		}

		AdUser newUser = adUserRepository.save(new AdUser(request.getUsername(), CommonUtils.md5(request.getUsername())));

		return new CreateUserResponse(newUser.getId(),
				newUser.getUsername(),
				newUser.getToken(), newUser.getCreateTime(), newUser.getUpdateTime());
	}
}
